package com.neusoft.controller;

import com.alibaba.fastjson.JSON;
import com.neusoft.common.JwtUtils;
import com.neusoft.common.Result;
import com.neusoft.pojo.User;
import com.neusoft.service.LoginService;
import com.neusoft.service.UserService;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwt;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired
    LoginService loginService;
    @Autowired
    UserService userService;

    @GetMapping("/{username}/{password}")
    public Result<?> login(@PathVariable("username") String username, @PathVariable("password")String password){
        Map<String,?> userMap = loginService.Login(username,password);
        if (userMap != null){
            HashMap<String, Object> map = new HashMap<>();
            map.put("userId",userMap.get("id"));
            map.put("username", username);
            map.put("password", password);
            String token = JwtUtils.createJwt(username, password, map);
            return Result.success(token);
        }
        return Result.error("400","请确认用户是否正确");
    }

    @PostMapping("/getUserInfo")
    public Result<?> getUserInfo(HttpServletRequest request){
        String authorization = request.getHeader("Authorization");
        if (StringUtils.isNotEmpty(authorization)){
            //2.替换Bearer+空格
            String token = authorization.replace("Bearer ", "");
            try {
                //  解密token
                Claims claims = JwtUtils.parseJwt(token);
                //4.获取clamis
                String uId = claims.get("userId") == null?"":claims.get("userId").toString();
                // 根据用户获取信息
                User user = userService.userByUserId(uId);
                return Result.success(user);
            }catch (RuntimeException e){
                return Result.error("400","token失效");
            }

        }else {
            return  Result.error("400","认证失败");
        }
    }

    @PostMapping
    public String Register(@RequestBody String json){
        Map<String,String> parse = (Map<String, String>) JSON.parse(json);
        int i = loginService.register(parse);
        return "success";
    }

    @PostMapping("/menu/menuAdd1234")
    public String menuAdd(@RequestBody String json){
        Map<String,String> parse = (Map<String, String>) JSON.parse(json);
        System.out.println(parse);
        return "Result.error()";
    }

}
